package jprint.base.util;

import java.io.FileInputStream;
import java.io.IOException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.PrintQuality;

public class PrintUtil {

    private static final float INCH_MM = 25.4f; // 1 inch = 25.4 mm

    public static void drawImage(String fileName, int count) {
        FileInputStream fin = null;
        try {
            DocFlavor dof = null;
            if (fileName.endsWith(".gif")) {
                dof = DocFlavor.INPUT_STREAM.GIF;
            } else if (fileName.endsWith(".jpg")) {
                dof = DocFlavor.INPUT_STREAM.JPEG;
            } else if (fileName.endsWith(".png")) {
                dof = DocFlavor.INPUT_STREAM.PNG;
            }

            PrintService ps = PrintServiceLookup.lookupDefaultPrintService();

            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            pras.add(OrientationRequested.PORTRAIT);

            pras.add(new Copies(count));
            pras.add(PrintQuality.HIGH);
            DocAttributeSet das = new HashDocAttributeSet();

            // 设置打印纸张的大小（以毫米为单位）
            das.add(new MediaPrintableArea(0, 0, 210, 296, MediaPrintableArea.MM));
            fin = new FileInputStream(fileName);

            Doc doc = new SimpleDoc(fin, dof, das);

            DocPrintJob job = ps.createPrintJob();

            job.print(doc, pras);
            fin.close();
            System.out.println("打印成功！文件：" + fileName + "数量为：" + count);
        } catch (IOException | PrintException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new PrintUtil().drawImage("webapp\\label.png", 1);
    }

    public static int mm2dot(int mm, int dpi) {
        // eg: A4 size = 210x297mm =>
        // 210 x (72 / 25.4) = 595.27, 297 x (72 / 25.4) = 841.88 =>
        // A4 size = 595x841 Dot
        float dpmm = dpi / INCH_MM;
        return (int) (mm * dpmm);
    }

    public static int dot2mm(int dot, int dpi) {
        float dpmm = dpi / INCH_MM;
        return (int) (dot / dpmm);
    }
}
